package com.yolo.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yolo.entity.*;
import com.yolo.entity.dto.*;
import com.yolo.common.annotation.Log;
import com.yolo.common.enums.BusinessType;
import com.yolo.entity.Dept;
import com.yolo.entity.Post;
import com.yolo.entity.dto.DeptDto;
import com.yolo.entity.dto.EmpConditionDto;
import com.yolo.entity.dto.EmpView;
import com.yolo.entity.vo.EmpViewVo;
import com.yolo.service.*;
import com.yolo.util.RedisUtil;
import com.yolo.util.Result;
import com.yolo.util.SmsUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 天蝎
 * @since 2021-04-12
 */
@RestController
@RequestMapping("/emp")
@CrossOrigin
public class EmpController {
    @Autowired
    private EmpViewService empViewService;

    @Autowired
    private PostService postService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpService empService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private SmsSendService smsSendService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RoleService roleService;
    @Autowired
    private EducationService educationService;

    @Autowired
    private PoliticalOutlookService politicalOutlookService;

/**
 * 龙哥登录模块
 */
    /**
     * 用户名密码登录
     *
     * @param login
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Login login) {
        String roleName="";
        Emp empData = empService.getOne(new QueryWrapper<Emp>().
                eq("phone", login.getPhone()).eq("password", login.getPassword()));
        if (empData != null) {
            redisUtil.set("empName", empData.getName());
            String[] split = empData.getRoleIds().split(",");
            List<Role> roles = roleService.list(new QueryWrapper<Role>()
                    .in("role_id", Arrays.asList(split)));
            for (int i = 0; i < roles.size(); i++) {
                String roleName1 = roles.get(i).getRoleName();
                if(roleName1!=null && !roleName1.equals(""))
                {
                    if (i == roles.size()-1) {
                        roleName += roles.get(i).getRoleName();
                    } else {
                        roleName += roles.get(i).getRoleName() + "/";
                    }
                }
            }
        }
        return Result.succ(MapUtil.builder()
                .put("empData", empData)
                .put("roleName", roleName)
        .map());

    }

    /**
     * 手机验证码，并进行等登录    （不完善）
     *
     * @param phoneLogin
     * @return
     */
    @RequestMapping("/phoneLogin")
    public Result phoneLogin(@RequestBody PhoneLogin phoneLogin) {
        String roleName="";
        Object code = redisUtil.get(phoneLogin.getPhone());
        if (phoneLogin.getValidationNumber().equals(code)) {
            Emp empData = empService.getOne(new QueryWrapper<Emp>().
                    eq("phone", phoneLogin.getPhone()));
            if (empData != null) {
                redisUtil.set("empName", empData.getName());
                String[] split = empData.getRoleIds().split(",");
                List<Role> roles = roleService.list(new QueryWrapper<Role>()
                        .in("role_id", Arrays.asList(split)));
                for (int i = 0; i < roles.size(); i++) {
                    String roleName1 = roles.get(i).getRoleName();
                    if(roleName1!=null && !roleName1.equals(""))
                    {
                        if (i == roles.size()-1) {
                            roleName += roles.get(i).getRoleName();
                        } else {
                            roleName += roles.get(i).getRoleName() + "/";
                        }
                    }
                }
            }




            redisUtil.set("empName", empData.getName());
            redisUtil.del(phoneLogin.getPhone());
            return Result.succ(MapUtil.builder()
                    .put("empData", empData)
                    .put("roleName", roleName)
                    .map());
        }
        return null;
    }

    /**
     * 通过角色id获取用户权限
     *
     * @param roleId
     * @return
     */
    @PostMapping("/resData")
    public Result resource(Integer roleId) {

        List<RoleResource> roleResourceData = roleResourceService.list(new QueryWrapper<RoleResource>().
                eq("role_id", roleId));

        Integer[] resourceArr = new Integer[roleResourceData.size()];
        int i = 0;
        for (RoleResource rr : roleResourceData) {
            resourceArr[i] = rr.getResourceId();
            i++;
        }
        String s = Arrays.toString(resourceArr);
        String[] split = s.substring(1, s.length() - 1).split(",");

        List<Resource> list = resourceService.list(new QueryWrapper<Resource>().
                in("resource_id", split));

        return Result.succ(list);
    }


    @PostMapping("/empResource")
    public Result resourceData(String ids) {
        String[] roleId = ids.split(",");
        List<RoleResource> roleResourceList = roleResourceService.list(new QueryWrapper<RoleResource>()
                .in("role_id", Arrays.asList(roleId)));
        Set<Integer> resourceId = new HashSet<>();
        roleResourceList.forEach(r -> {
            resourceId.add(r.getResourceId());
        });
        List<Resource> empResource = resourceService.list(new QueryWrapper<Resource>()
                .in("resource_id", resourceId));
        List<String> resourceName = new ArrayList<>();
        empResource.forEach(e -> {
            resourceName.add(e.getResourceName());
        });
        return Result.succ(resourceName);
    }

    /**
     * 验证手机号码是否存在
     *
     * @param phone
     * @return
     */
    @RequestMapping("/phone")
    public boolean phone(String phone) {
        Emp empData = empService.getOne(new QueryWrapper<Emp>().
                eq("phone", phone));
        return empData != null;
    }

    /**
     * 通过手机号获取验证码
     *
     * @return
     */
    @RequestMapping("/getValidationCode/{phone}")
    public Result generateValidationCode(@PathVariable String phone) throws Exception {
        String uuidCode = SmsUtil.getUUIDCode();
        Object o = redisUtil.get(phone);
        if (StringUtils.isEmpty(o)) {
            boolean isSend = smsSendService.send(phone, "", uuidCode);
            if (isSend) {
                redisUtil.set(phone, uuidCode, 300);
                return Result.succ("短信发送成功");
            }
            return Result.succ("短信发送失败，手机号错误");
        }
        return Result.succ("验证码已发送");
    }


    /**
     * @param empId
     * @param password
     * @param newPassword
     * @return
     */
    @PostMapping("/changePassword")
    public Result changePassword(Integer empId, String password, String newPassword, String code, String phone) {
        Emp empData = empService.getOne(new QueryWrapper<Emp>().
                eq("emp_id", empId).eq("password", password));
        if (empData != null) {
            if (newPassword.length() < 8) {
                return Result.succ("2");
            }
            if (password.equals(newPassword)) {
                return Result.succ("1");
            }
            if (code.equals("") || code.equals(null) || code == null) {
                return Result.succ("3");
            }

            Object vCode = redisUtil.get(phone);
            if (!code.equals(vCode)) {
                return Result.succ("4");
            }
            Emp emp = new Emp();
            emp.setEmpId(empId);
            emp.setPassword(newPassword);
            boolean flag = empService.updateById(emp);
            redisUtil.del(phone);
            return Result.succ(emp);
        }
        return Result.succ("-1");
    }

    /**
     * 老唐员工管理模块
     */

    @Log(title = "用户模块", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void exportDept(HttpServletResponse response) {
        try {
            List<Dept> list = deptService.list();
            @SuppressWarnings("resource")
            HSSFWorkbook wb = new HSSFWorkbook();
            //HSSFCellStyle style = ExcelStyleUtil.getStyle(wb);
            HSSFSheet sheet = wb.createSheet("记录");
            HSSFRow row;
            int columnIndex = 0;
            row = sheet.createRow(0);
            row.setHeight((short) (22.50 * 10));//设置行高
            row.createCell(columnIndex).setCellValue("序号");
            row.createCell(++columnIndex).setCellValue("员工编号");
            row.createCell(++columnIndex).setCellValue("员工名称");
            row.createCell(++columnIndex).setCellValue("员工编号");
            row.createCell(++columnIndex).setCellValue("员工名称");
            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                Dept entity = list.get(i);
                columnIndex = 0;
                row.createCell(columnIndex).setCellValue(i + 1);
                row.createCell(++columnIndex).setCellValue(entity.getDeptId());
                row.createCell(++columnIndex).setCellValue(entity.getDeptName());
            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));
            //列宽自适应
            for (int i = 0; i <= 11; i++) {
                sheet.autoSizeColumn(i);
            }
            String title = "czjl_all";
            response.setHeader("Content-disposition", "attachment;fileName=" + title + ".xls");
            response.setContentType("application/octet-stream;charset=utf-8");
            OutputStream ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除员工信息
     */
    @Log(title = "用户模块", businessType = BusinessType.DELETE)
    @PostMapping("/empDeleteById/{empId}")
    public Result empDeleteById(@PathVariable("empId") int empId) {
        QueryWrapper<Emp> qw = new QueryWrapper<>();
        qw.eq("emp_id", empId);
        empService.remove(qw);
        return null;
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    @Log(title = "用户模块", businessType = BusinessType.QUERY)
    @GetMapping("/roleList")
    public Result roleList() {
        return Result.succ(roleService.list());
    }

    /**
     * 图片上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadImg")
    public String upload(@RequestParam("image") MultipartFile file) throws IOException {
        String path = ResourceUtils.getURL("classpath:").getPath() + "static/";
        File descDir = new File(path);
        if (!descDir.exists()) {
            descDir.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        file.transferTo(new File(path + fileName));
        return "http://localhost:8888/" + fileName;
    }

    /**
     * 修改员工信息
     *
     * @param empView
     * @return
     */
    @Log(title = "用户模块", businessType = BusinessType.UPDATE)
    @PostMapping("/empAmend")
    public Result empAmend(@RequestBody EmpView empView) {
        Emp emp = new Emp();
        BeanUtils.copyProperties(empView, emp);
        empService.updateById(emp);
        return null;
    }


    /**
     * 根据id查询员工信息
     *
     * @param empId
     * @return
     */
    @Log(title = "用户模块", businessType = BusinessType.QUERY)
    @PostMapping("/empListById/{empId}")
    public Result empListById(@PathVariable("empId") int empId) {
        QueryWrapper<EmpView> qw = new QueryWrapper<>();
        qw.eq("emp_id", empId);
        return Result.succ(empViewService.getOne(qw));
    }

    /**
     * 查询所有学历
     *
     * @return
     */
    @GetMapping("/educationList")
    public Result educationList() {
        return Result.succ(educationService.list());
    }

    /**
     * 查询所有政治面貌
     *
     * @return
     */
    @GetMapping("/politicalList")
    public Result politicalList() {
        return Result.succ(politicalOutlookService.list());
    }

    /**
     * 查询所有员工岗位
     *
     * @return
     */
    @GetMapping("/postList")
    public Result postList() {
        return Result.succ(postService.list());
    }

    /**
     * 添加员工信息
     *
     * @param empDto
     * @param posts
     * @return
     */
    @Log(title = "用户模块", businessType = BusinessType.INSERT)
    @PostMapping("/addEmp/{posts}")
    public Result addEmp(@RequestBody EmpDto empDto, @PathVariable("posts") ArrayList<String> posts) {
        Emp emp = new Emp();
        BeanUtils.copyProperties(empDto, emp);

        QueryWrapper<Post> qw = new QueryWrapper<>();
        switch (posts.size()) {
            case 1:
                posts.get(0);
                qw.eq("post_name", posts.get(0));
                break;
            case 2:
                posts.get(0);
                posts.get(1);
                qw.eq("post_name", posts.get(0)).or().eq("post_name", posts.get(1));
                break;
            case 3:
                posts.get(0);
                posts.get(1);
                posts.get(2);
                qw.eq("post_name", posts.get(0)).or().eq("post_name", posts.get(1)).or().eq("post_name", posts.get(2));
                break;
        }
        String ids = "";
        List<Post> list = postService.list(qw);
        for (Post s : list) {
            ids += s.getPostId() + ",";
        }
        if (ids != null && !ids.equals("")) {
            emp.setPostIds(ids);
        }
        empService.save(emp);
        return Result.succ(null);
    }


    /**
     * 带分页的查询数据，以及条件查询
     *
     * @param pageIndex
     * @param pageSize
     * @param empQuery
     * @return
     */
    @Log(title = "用户模块", businessType = BusinessType.QUERY)
    @PostMapping("/{pageNo}/{limit}")
    public Result empListPage(@PathVariable("pageNo") int pageIndex, @PathVariable("limit") int pageSize, @RequestBody EmpConditionDto empQuery) {
        QueryWrapper<EmpView> wrapper = getWrapper(empQuery);
        Page<EmpView> page = empViewService.page(new Page<EmpView>(pageIndex, pageSize), wrapper);
        for (EmpView e : page.getRecords()) {
            String[] s1 = e.getPostIds().split(",");
            List<Post> list1 = postService.list(new QueryWrapper<Post>().in("post_id", s1));
            e.setPosts(list1);
        }
        List<EmpViewVo> empViewVos = new ArrayList<>();
        List<EmpView> records = page.getRecords();
        records.forEach(r -> {
            EmpViewVo empViewVo = new EmpViewVo();
            BeanUtils.copyProperties(r, empViewVo);
            String postNames = "";
            List<Post> posts = r.getPosts();
            for (int i = 0; i < posts.size(); i++) {
                if (i == (posts.size() - 1)) {
                    postNames += posts.get(i).getPostName();
                } else {
                    postNames += posts.get(i).getPostName() + "  /  ";
                }
            }
            empViewVo.setPostNames(postNames);
            empViewVos.add(empViewVo);
        });

        return Result.succ(MapUtil.builder()
                .put("data", empViewVos)
                .put("count", page.getTotal())  // 总记录数
                .map()
        );
    }

    /**
     * 分页条件的封装方法
     *
     * @param empQuery
     * @return
     */
    private QueryWrapper<EmpView> getWrapper(EmpConditionDto empQuery) {
        QueryWrapper<EmpView> qw = new QueryWrapper<>();
        if (empQuery != null) {
            if (!StringUtils.isEmpty(empQuery.getName())) {
                qw.like("name", empQuery.getName());
            } else if (!StringUtils.isEmpty(empQuery.getState())) {
                qw.eq("state", empQuery.getState());
            }
        }
        qw.orderByAsc("emp_id");
        return qw;
    }

    /**
     * 部门中的岗位级联选择器查询数据
     *
     * @return
     */
    @RequestMapping("/deptListName")
    public Result deptListName() {
        List<Dept> list = deptService.list(null);
        List<DeptDto> deptDtos = new ArrayList<>();
        for (Dept l : list) {
            Dept byId = deptService.getById(l.getDeptId());
            DeptDto deptDto = new DeptDto();
            deptDto.setValue(byId.getDeptId());
            deptDto.setLabel(byId.getDeptName());
            QueryWrapper<Post> dept_id = new QueryWrapper<Post>().eq("dept_id", l.getDeptId());

            List<Post> list1 = postService.list(dept_id);
            List<DeptDto> depts = new ArrayList<>();
            for (Post p : list1) {
                DeptDto dto = new DeptDto();
                dto.setValue(p.getPostId());
                dto.setLabel(p.getPostName());
                depts.add(dto);
            }
            deptDto.setChildren(depts);
            deptDtos.add(deptDto);
        }
        return Result.succ(deptDtos);
    }
}
